<template>
  <div>
    <el-dialog
      :before-close="handleClose"
      :title="status === 'Add' ? '新增商品' : '编辑商品'"
      :visible.sync="dialogVisible"
      width="650px"
    >
      <div>
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          class="demo-ruleForm"
          label-width="100px"
        >
          <el-form-item label="背景名称" prop="name">
            <el-input
              v-model="ruleForm.name"
              placeholder="请输入背景名称"
              style="width: 80%;"
            ></el-input>
          </el-form-item>

          <el-form-item label="展示图片" prop="picture">
            <el-upload
              :http-request="customizeUpload"
              :on-success="handleSuccess"
              :show-file-list="false"
              action=""
              class="avatar-uploader"
            >
              <img
                v-if="ruleForm.picture"
                :src="ruleForm.picture"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="效果选择" prop="is_dynamic">
            <el-radio-group v-model="ruleForm.is_dynamic">
              <el-radio :label="0">静态效果</el-radio>
              <el-radio :label="1">动态效果</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            label="静态效果"
            prop="effect_picture"
          >
            <el-upload
              :http-request="customizeUpload"
              :on-success="handleSuccess1"
              :show-file-list="false"
              action=""
              class="avatar-uploader"
            >
              <img
                v-if="ruleForm.effect_picture"
                :src="ruleForm.effect_picture"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>

          <el-form-item
            label="动态效果"

          >
            <el-upload
              :before-upload="handleError2"
              :http-request="customizeUpload"
              :on-success="handleSuccess2"
              :show-file-list="false"
              accept="video/*"
              action=""
              class="avatar-uploader"
            >
              <video
                v-if="ruleForm.special"
                :src="ruleForm.special"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>


          <el-form-item label="官方分类" prop="type">
            <el-input
              v-model="ruleForm.type"
              placeholder="官方分类"
              style="width: 80%;"
            ></el-input>
          </el-form-item>


          <el-form-item label="是否免费" prop="is_free">
            <el-radio-group v-model="ruleForm.is_free">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item v-if="!ruleForm.is_free" label="天数&价格">
            <div
              v-for="(item, index) in days_price_arr"
              :key="'天价' + index"
              :class="[index ? 'mt-2' : '']"
            >
              <el-input
                v-model.number="item.day"
                class="mr-3"
                style="width:200px"
              >
                <span slot="suffix">天</span>
              </el-input>
              <el-input
                v-model.number="item.price"
                class="mr-3"
                style="width:200px"
              >
                <span slot="suffix">金币</span>
              </el-input>
              <el-button v-if="index" @click.prevent="removePrice(item)"
              >删除
              </el-button
              >
            </div>
          </el-form-item>
          <el-form-item v-if="!ruleForm.is_free">
            <el-button @click="addPrice">新增</el-button>
          </el-form-item>
          <el-form-item label="出售状态" prop="sell_status">
            <el-radio-group v-model="ruleForm.sell_status">
              <el-radio :label="1">上架</el-radio>
              <el-radio :label="2">下架</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button
          :loading="submitLoading"
          type="primary"
          @click="submitForm('ruleForm')"
        >提交</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { postData, putData } from '@/api/room/backgroundManage'

export default {
  name: 'addEditModal',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    // 模态框的状态 Add 为新增  Edit为编辑
    status: {
      type: String,
      default: ['Add']
    },
    // 选择类别选择项
    categoryOption: {
      type: Array,
      default: () => []
    },
    // 风格标签选择项
    styleLabelOptions: {
      type: Array,
      default: () => []
    },
    rowData: {
      type: Object,
      default: () => {
      }
    }
  },
  data() {
    return {
      dataTime: {
        startTime: null,
        endTime: null
      },
      submitLoading: false,
      ruleForm: {
        name: null, // 商品名称
        picture: null, // 图片url
        effect_picture: null, // 静态效果url，
        special: null,//动态效果url
        is_dynamic: 0,//是否是动效图片
        is_free: 1, // 展示位置：1：半屏；2：全屏；3：右侧，必须
        day_price: null, // 天数与价格
        sell_status: 1, // 出售状态：1：上架；0：下架，必须
        type: ''//官方分类
      },
      days_price_arr: [{ price: undefined, day: undefined }],

      rules: {
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        picture: [
          { required: true, message: '请上传展示图片', trigger: 'blur' }
        ],
        effect_picture: [
          { required: true, message: '请上传/输入静态效果', trigger: 'blur' }
        ],
        special: [
          { required: true, message: '请上传/输入动态效果', trigger: 'blur' }
        ],
        sell_status: [
          { required: true, message: '请选择出售状态', trigger: 'blur' }
        ],
        type: [{
          required: true, message: '请输入官方分类', trigger: 'blur'
        }],
        is_free: [
          { required: true, message: '请选择是否免费', trigger: 'blur' }
        ],
        is_dynamic: [
          { required: true, message: '请选择效果', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    handleClose(done) {
      this.$emit('update:dialogVisible', false)
      this.$emit('update:status', 'Add')
      this.resetForm('ruleForm')
    },
    submitForm(formName) {
      let data = {}
      for (let key in this.ruleForm) {
        data[key] = this.ruleForm[key]
      }
      data.day_price = JSON.stringify(this.days_price_arr)

      this.$refs[formName].validate(async valid => {
        if (valid) {
          this.submitLoading = true
          let detail
          // 新增活动商品
          if (this.status === 'Add') {
            detail = await postData(data)
          } else {
            // 编辑
            let data1 = { id: this.id, ...data }
            detail = await putData(this.rowData.id, data1)
          }
          if (detail.code === 200) {
            this.$message.success(
              this.status === 'Add' ? '添加成功!' : '编辑成功'
            )
            this.$emit('update:dialogVisible', false)
            this.$emit('updateTable')

            this.ruleForm = {
              name: null, // 商品名称
              picture: null, // 图片url
              effect_picture: null, // 静态效果url
              special: null,//动态效果url
              is_dynamic: 0,// 效果：0：静态效果；2：动态效果；
              is_free: 1, // 展示位置：1：半屏；2：全屏；3：右侧，必须
              day_price: null, // 天数与价格
              sell_status: 1,
              type: null
            }
            this.$emit('update:status', 'Add')
          }
          this.submitLoading = false
        } else {
          this.submitLoading = false

          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.ruleForm = {
        name: null, // 商品名称
        picture: null, // 图片url
        effect_picture: null, // 静态效果url
        special: null,//动态效果url
        is_dynamic: 0,//效果
        is_free: 1, // 展示位置：1：半屏；2：全屏；3：右侧，必须
        day_price: null, // 天数与价格
        sell_status: 1,
        type: null
      }
      this.days_price_arr = [{ price: undefined, day: undefined }]
    },
    handleSuccess() {
      this.ruleForm.picture = this.ossLastImgUrl
    },
    handleSuccess1() {
      this.ruleForm.effect_picture = this.ossLastImgUrl
    },
    handleSuccess2() {
      this.ruleForm.special = this.ossLastImgUrl
    },
    handleError2(file) {
      if (file.type !== 'video/mp4') {
        this.$message.error('上传特效只能为 MP4 格式!')
        return false
      } else {
        return true
      }
    },
    addPrice() {
      this.days_price_arr.push({ day: undefined, price: undefined })
    },
    removePrice(item) {
      let index = this.days_price_arr.indexOf(item)
      if (index !== -1) {
        this.days_price_arr.splice(index, 1)
      }
    }
  },
  watch: {
    async status(newVal) {
      /* 当 status 为 Edit 则 为编辑框, 需要完成数据的回显   */
      let row = JSON.parse(JSON.stringify(this.rowData))
      if (newVal === 'Edit') {
        this.ruleForm.name = row.name
        this.ruleForm.picture = row.picture
        this.ruleForm.effect_picture = row.effect_picture
        this.ruleForm.special = row.special
        this.ruleForm.is_dynamic = row.is_dynamic
        this.ruleForm.is_free = row.is_free
        this.ruleForm.sell_status = row.sell_status
        this.ruleForm.type = row.room_background_type.reduce((pre, cur) => {
          return pre + cur.tid + ','
        }, '')

        if (
          row.room_background_products_price.length &&
          row.room_background_products_price.length > 0
        ) {
          this.days_price_arr = row.room_background_products_price.map(item => {
            let data = {}
            data.price = item.price
            data.day = item.day
            return data
          })
        } else {
          this.days_price_arr = [{ day: undefined, price: undefined }]
        }
      }
    }
  }
}
</script>

<style scoped>
::v-deep.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
